#include <windows.h>
#include <d3d9.h>
#include <d3dx9.h>
#include "direct3d.h"
#include "sprite.h"
#include "cDayState.h"
#include "cWorld.h"


HWND hWnd;
IDirect3DDevice9* worldDevice;


LRESULT WINAPI MsgProc( HWND hWndTmp, UINT msg, WPARAM wParam, LPARAM lParam );

void doScene();
void doInput();


int const xRes=800,yRes=600;


cNight *night;
cMorning *morn;
cWorld *world;

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{	
	if(!D3DInit(hInstance,xRes,yRes,true,true,&worldDevice,MsgProc,"World of states",hWnd))
		return false;
	cSprite::SetDevice(worldDevice);

	night=new cNight("night_bg.jpg","night_creat.jpg");
	morn=new cMorning("day_bg.jpg","day_creat.jpg");
	world=new cWorld(3);
	
	MSG msg;
    while( msg.message != WM_QUIT )
    {
		if( PeekMessage(&msg,NULL,0U,0U,PM_REMOVE ) )
        {
		    TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
		else
		{
			doScene();
			doInput();
		}
    }

	return 0;
}

void doScene()
{
	worldDevice->BeginScene();
	worldDevice->Clear(0,0,D3DCLEAR_TARGET,0x00000000,1.0f,0);

	world->Draw();


	worldDevice->EndScene();
	worldDevice->Present(0,0,0,0);
}

void doInput()
{
	if(GetAsyncKeyState(VK_ESCAPE))
		PostQuitMessage(0);
	
	if(GetAsyncKeyState(VK_UP))
		world->setPopulation(world->getPopulation()+1);
	if(GetAsyncKeyState(VK_DOWN))
		world->setPopulation(world->getPopulation()-1);

	if(GetAsyncKeyState(VK_LEFT))
		world->setDayState(night);
	if(GetAsyncKeyState(VK_RIGHT))
		world->setDayState(morn);

}

LRESULT WINAPI MsgProc( HWND hWndTmp, UINT msg, WPARAM wParam, LPARAM lParam )
{
	switch (msg)
	{
		case WM_CLOSE:
		case WM_DESTROY:
			PostQuitMessage(0);
	}
	return DefWindowProc(hWndTmp, msg, wParam, lParam);
}
